#include "stc15f2k60s2.h"
#include "Seg.h"
#include "Tim.h"
#include "Key.h"
#include "LED.h"
#include "stdio.h"
#include "Ds1302.h"
unsigned long ulms,ucSeg_Dly;
unsigned char ucSec;
unsigned char pucSeg_Buf[9],pucSeg_Code[8],ucSeg_Pos;
unsigned char ucKey_Dly,ucKey_Old;
unsigned char ucState=1;
unsigned char pucRtc[3]={23,58,50};
void Seg_Proc();
void Key_Proc();
void main(){
	Cls_Peripheral() ;
	Timer1Init();
	Set_RTC(pucRtc);
	while(1){
		Key_Proc() ;
		Seg_Proc();
	}
}
void Time_1(void) interrupt 3 //定时器1中断函数
{ 
	 ulms++; 
	 if(!(ulms % 1000)) { 
		 ucSec++; 
	 } 
	 if(++ucKey_Dly>=20) ucKey_Dly=0;
	if(++ucSeg_Dly>=500) ucSeg_Dly=0;
	 Seg_Disp(pucSeg_Code, ucSeg_Pos);
	 if(++ucSeg_Pos>=8) ucSeg_Pos=0;
} 
void Key_Proc(void) 
{ 
	 unsigned char ucKey_Val, ucKey_Down, ucKey_Up; 
	 if(ucKey_Dly) return; 
		ucKey_Dly = 1; 
	 ucKey_Val = Key_Read(); 
	 ucKey_Down = ucKey_Val & (ucKey_Old ^ ucKey_Val); 
	 ucKey_Up = ~ucKey_Val & (ucKey_Old ^ ucKey_Val); 
	 ucKey_Old = ucKey_Val; 
	 if(ucKey_Down==4)  { 
		 ucState++;
		 if(ucState==2) 
			 ucState=0;
		 
	 } 
	Led_Disp(ucState+1);
}
void Seg_Proc(){
	if(ucKey_Dly) return;
	ucKey_Dly=1;
	switch (ucState){
		case 0:
			sprintf(pucSeg_Buf, "1 %06u",(unsigned int)ucSec) ;
		break;
		case 1:
			Read_RTC(pucRtc) ;
			sprintf(pucSeg_Buf, "2 %02d%02d%02d",(unsigned int)pucRtc[0],(unsigned int)pucRtc[1],(unsigned int)pucRtc[2]) ;
		break;
	}
	Seg_Tran(pucSeg_Buf, pucSeg_Code);
}